//
//  SettingViewController.swift
//  todaySwift
//
//  Created by ChokWah on 2018/3/18.
//  Copyright © 2018年 ChokWah. All rights reserved.
//

import UIKit
import Kingfisher

class SettingViewController: UITableViewController {

    var sections = [[SettingModel]]()
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        // 获取缓存文件大小
        calculateDiskCacheSize()
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return sections.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return sections[section].count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.cwc_dequeueReusableCell(indexPath: indexPath) as SettingCell
        let rows = sections[indexPath.section]
        
        switch indexPath.section {
        case 0:
            switch indexPath.row {
            case 0: // 第一行，清理缓存
            NotificationCenter.default.addObserver(self, selector: #selector(loadCacheSize(notification:)), name: NSNotification.Name(rawValue: "cacheSizeM"), object: nil)
            case 1: // 第二行，改变字体大小
                NotificationCenter.default.addObserver(self, selector: #selector(changeFontSize(notification:)), name: NSNotification.Name(rawValue: "fontSize"), object: nil)
            case 2:
                cell.selectionStyle = .none
            case 3:
                NotificationCenter.default.addObserver(self, selector: #selector(changeNetworkMode(notification:)), name: NSNotification.Name(rawValue: "networkMode"), object: nil)
            case 4:
                NotificationCenter.default.addObserver(self, selector: #selector(changePlayNotice(notification:)), name: NSNotification.Name(rawValue: "playNotice"), object: nil)
            default: break
            }
        default: break
        }
        cell.setting = rows[indexPath.row]
        return cell
    }
    
    
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 10))
        view.backgroundColor = UIColor.globalBackgroundColor()
        return view
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        switch indexPath.section {
        case 0:
            switch indexPath.row {
            case 0: // 第一行，清理缓存
                clearCacheAlertController()
            case 1: // 设置字体大小
                setupFontAlertController()
            case 3: // 非WiFi，网络流量
                setupNetworkAlertController()
            case 4: // 非WiFi网络播放视频提醒
                setupPlayNoticeAlertController()
            default: break
            }
        case 1 :
            switch indexPath.row {
            case 0:
                let offDownloadVC = OffineDownloadController()
                offDownloadVC.navigationItem.title = "离线下载"
                navigationController?.pushViewController(offDownloadVC, animated: true)
            default: break
            }
        default: break
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension SettingViewController {
    
    // 改变网络播放提醒
    @objc fileprivate func changePlayNotice(notification: Notification) {
        let userInfo = notification.userInfo as! [String : AnyObject]
        let indexPath = IndexPath(row: 4, section: 0)
        let cell = tableView.cellForRow(at: indexPath) as! SettingCell
        cell.rightLabel.text = userInfo["playNotice"] as? String
    }
    
    // 非WiFi 网络播放提醒
    fileprivate func setupPlayNoticeAlertController() {
        let AlertController = UIAlertController(title: "非WiFi 网络播放提醒", message: nil, preferredStyle: .actionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let onceAction = UIAlertAction(title: "提醒一次",  style: .default, handler: {(_) in
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "playNotice"), object: self, userInfo: ["playNotice": "提醒一次"])
        })
        let everyTimeAction = UIAlertAction(title: "每次提醒", style: .default, handler: {(_) in
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "playNotice"), object: self, userInfo: ["playNotice": "每次提醒"])
        })
        AlertController.addAction(cancelAction)
        AlertController.addAction(onceAction)
        AlertController.addAction(everyTimeAction)
        present(AlertController, animated: true, completion: nil)
    }
    
    // 改变网络模式
    @objc fileprivate func changeNetworkMode(notification: Notification) {
        let userInfo = notification.userInfo as! [String : AnyObject]
        let indexPath = IndexPath(row: 3, section: 0)
        let cell = tableView.cellForRow(at: indexPath) as! SettingCell
        cell.rightLabel.text = userInfo["networkMode"] as? String
    }
    
    // 非WiFi 网络流量
    fileprivate func setupNetworkAlertController() {
        let AlertController = UIAlertController(title: "非WiFi 网络流量", message: nil, preferredStyle: .actionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let bastAction = UIAlertAction(title: "最佳效果（下载大图）",  style: .default, handler: {(_) in
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "networkMode"), object: self, userInfo: ["networkMode": "最佳效果（下载大图）"])
        })
        let betterAction = UIAlertAction(title: "较省流量（智能下图）", style: .default, handler: {(_) in
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "networkMode"), object: self, userInfo: ["networkMode": "较省流量（智能下图）"])
        })
        let normalAction = UIAlertAction(title: "极省流量（智能下图）",  style: .default, handler: {(_) in
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "networkMode"), object: self, userInfo: ["networkMode": "极省流量（智能下图）"])
        })

        AlertController.addAction(cancelAction)
        AlertController.addAction(normalAction)
        AlertController.addAction(betterAction)
        AlertController.addAction(bastAction)
        present(AlertController, animated: true, completion: nil)
    }
    
    // 改变字体大小
    @objc fileprivate func changeFontSize(notification: Notification) {
        let userInfo = notification.userInfo as! [String : AnyObject]
        let indexPath = IndexPath(row: 1, section: 0)
        let cell = tableView.cellForRow(at: indexPath) as! SettingCell
        cell.rightLabel.text = userInfo["fontSize"] as? String
    }
    
    // 设置字体大小
    fileprivate func setupFontAlertController() {
        let AlertController = UIAlertController(title: "设置字体大小", message: nil, preferredStyle: .actionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let smallAction = UIAlertAction(title: "小",  style: .default, handler: {(_) in
             NotificationCenter.default.post(name: NSNotification.Name(rawValue: "fontSize"), object: self, userInfo: ["fontSize": "小"])
        })
        let middleAction = UIAlertAction(title: "中", style: .default, handler: {(_) in
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "fontSize"), object: self, userInfo: ["fontSize": "中"])
        })
        let bigAction = UIAlertAction(title: "大",  style: .default, handler: {(_) in
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "fontSize"), object: self, userInfo: ["fontSize": "大"])
        })
        let largeAction = UIAlertAction(title: "特大", style: .default, handler: {(_) in
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "fontSize"), object: self, userInfo: ["fontSize": "特大"])
        })
        AlertController.addAction(cancelAction)
        AlertController.addAction(smallAction)
        AlertController.addAction(middleAction)
        AlertController.addAction(largeAction)
        AlertController.addAction(bigAction)
        present(AlertController, animated: true, completion: nil)
    }
    
    // 从沙盒中获取缓存文件大小
    fileprivate func calculateDiskCacheSize(){
        let cache = KingfisherManager.shared.cache
        cache.calculateDiskCacheSize { (size) in
            let sizeM = Double(size) / 1024.0 / 1024.0
            let sizeString = String(format: "%.2fM", sizeM)
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "cacheSizeM"), object: self, userInfo: ["cacheSizeM": sizeString])
        }
    }
    
    // 获取缓存大小，显示cell
    @objc fileprivate func loadCacheSize(notification: Notification) {
        let userInfo = notification.userInfo as! [String : AnyObject]
        let indexPath = IndexPath(row: 0, section: 0)
        let cell = tableView.cellForRow(at: indexPath) as! SettingCell
        cell.rightLabel.text = userInfo["cacheSizeM"] as? String
    }
    
    // 清理缓存方法
    fileprivate func clearCacheAlertController() {
        let AlertController = UIAlertController(title: "清理所有缓存？问答，草稿，以及图片都会被清除", message: nil, preferredStyle: .actionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let okAction = UIAlertAction(title: "确定", style: .default, handler: {(_) in
            let cache = KingfisherManager.shared.cache
            cache.clearDiskCache()
            cache.clearMemoryCache()
            cache.cleanExpiredDiskCache(completion: nil)
            let sizeString = "0.00M"
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "cacheSizeM"), object: self, userInfo: ["cacheSizeM": sizeString])
        })
        AlertController.addAction(cancelAction)
        AlertController.addAction(okAction)
        present(AlertController, animated: true, completion: nil)

    }
}

extension SettingViewController {
    fileprivate func setupUI() {
        
        let cellPlist = NSArray(contentsOfFile: Bundle.main.path(forResource: "settingPlist.plist", ofType: nil)!) as! [Any]
        sections = cellPlist.flatMap ({ section in
            (section as! [Any]).flatMap({ row in
                SettingModel.deserialize(from: row as! NSDictionary)
            })
        })
        tableView.cwc_registerCell(cell: SettingCell.self)
        tableView.rowHeight = 44
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false
        
        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }
}
